import React, {FC, useCallback, useEffect, useMemo, useState} from "react";
import {DatePicker} from "antd";
import Config from "../../Config.tsx";
import dayjs from "dayjs";
import "dayjs/locale/zh";
import "dayjs/locale/en";
import {getItem} from "../../services/LocalDataService.tsx";

interface SelectDateProps {
    value?: any,
    ds?: any,
    picker?: "time" | "date" | "week" | "month" | "quarter" | "year",
    disabled: boolean,
    onChange: Function,
    comProps: any
}

const SelectDate: FC<SelectDateProps> = (props) => {
    const [date, setDate] = useState<any>();

    const handleChange: Function = useCallback((date: any, dateStr: string) => {
        setDate(date);
        props.onChange && props.onChange(dateStr);
    }, [props.onChange])

    useEffect(() => {
        const {ds = {}, picker = "date"}: {
            ds?: any,
            picker?: "time" | "date" | "week" | "month" | "quarter" | "year"
        } = props;
        let newValue = ds.value || props.value;
        if (newValue) {
            setDate(dayjs(newValue, Config.dateFormat[picker], getItem(Config.localLang)))
        }
    }, [props.ds, props.picker]);

    useEffect(() => {
        if(date && !props.value) {
            setDate(undefined)
        }
    }, [props.value]);

    const renderSelectDate = useMemo(() => {
        const {picker = "date", comProps = {}}: {
            picker?: "time" | "date" | "week" | "month" | "quarter" | "year",
            comProps: any
        } = props;

        const params = {
            ...comProps,
            value: date,
            picker: picker === "time" ? "date" : picker,
            disabled: props.disabled,
            showTime: picker === "time",
            onChange: handleChange,
            style: {width: "100%"}
        }
        if (comProps.disabledDate) {
            params.disabledDate = (current: any) => {
                return current && (current > dayjs(comProps.disabledDate[1], Config.dateFormat[picker], getItem(Config.localLang)).endOf('day') || current < dayjs(comProps.disabledDate[0], Config.dateFormat[picker], getItem(Config.localLang)))
            }
        }
        if(comProps.defaultPickerValue) {
            params.defaultPickerValue = [dayjs(comProps.defaultPickerValue[0], Config.dateFormat[picker], getItem(Config.localLang)), dayjs(comProps.defaultPickerValue[1], Config.dateFormat[picker], getItem(Config.localLang))]
        }
        return (
            <div className="sf_core_select_date">
                <DatePicker
                    {...params}
                />
            </div>
        )
    }, [date, props.picker, props.disabled, props.onChange, props.comProps]);
    return (renderSelectDate);
};

export default React.memo(SelectDate);